package com.example.goodrubish;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.goodrubish.API.Okhttp_work;
import com.example.goodrubish.Fragment.SearchFragment;
import com.example.goodrubish.Garbage.History_adapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class History extends AppCompatActivity {

    private List<String> newsList=new ArrayList<>();
    SharedPreferences sp,sp1;
    TextView textView;
    private Button button;
    String historyname;
    String url_garbage="http://api.tianapi.com/txapi/lajifenlei/index?key=8edca382d393d0c5f84996d0e8946b96&word=";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        button = findViewById(R.id.bt_delete);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog alertDialog = new AlertDialog.Builder(History.this).setTitle("删除历史记录")
                        .setMessage("是否确定删除所有历史记录：")
                        .setNeutralButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                SharedPreferences.Editor editor = sp.edit();
                                editor.remove("key_history");
                                editor.commit();
                                Intent intent=new Intent();
                                intent.setClass(History.this, History.class);
                                startActivity(intent);
                                finish();
                            }
                        })
                        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).create();
                alertDialog.show();
            }
        });
        init_list();
        History_adapter adapter=new History_adapter(History.this, R.layout.history_item, newsList);
        ListView listView=findViewById(R.id.listview);
        listView.setAdapter(adapter);

        ListView history_View=findViewById(R.id.listview);
        history_View.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                historyname = newsList.get(i);
                init_search();
            }
        });
    }
    private void init_list() {
        sp1 = getSharedPreferences("config",Context.MODE_PRIVATE);
        String name1 = sp1.getString("name",null);
        sp = getSharedPreferences(name1, Context.MODE_PRIVATE);
        String tjson = sp.getString("key_history",null);
        if(tjson!=null){
            Gson gson = new Gson();
            List<String> newsList1=new ArrayList<>();
            newsList1 = gson.fromJson(tjson, new TypeToken<List<String>>(){}.getType());
            for(int i=newsList1.size()-1;i>=0;i--){
                newsList.add(newsList1.get(i));
            }
        }else{
            newsList.add("无历史记录");
        }
    }

    public void init_search() {
        View view = getWindow().peekDecorView();
        if (view != null) {//这里是网络访问的代码，获取服务
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        initData_search();
    }

    Handler handler_search=new Handler(new Handler.Callback() {//首先通过handler发送信息
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0:
                    Toast.makeText(History.this,"网络错误",Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    String json=(String)msg.obj;
                    try{
                        SearchFragment.Search_JSON=new JSONObject(json);
                        Intent intent=new Intent();
                        intent.setClass(History.this, Detail.class);
                        startActivity(intent);		//进行页面跳转
                        finish();
                        break;
                    }catch (JSONException e){
                        e.printStackTrace();
                    }
                default:
                    throw new IllegalStateException("Unexpected value: " + msg.what);
            }
            return false;
        }
    });

    private void initData_search(){
        if(TextUtils.isEmpty(historyname)){//如果内容为空，弹出toast消息，不为空则执行164行以后的代码
            Toast.makeText(History.this,"跳转失败",Toast.LENGTH_SHORT).show();
        }
        else{
            Okhttp_work.OkHttpGet(url_garbage+historyname, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String content=response.body().string();
                    Message message=new Message();
                    message.what=1;
                    message.obj=content;
                    handler_search.sendMessageDelayed(message,1000);
                }
            });
        }
    }
}